package com.stellar.circle.domain.sChatMessage.impl;

import com.stellar.circle.basic.entity.SChatMessage;
import com.stellar.circle.basic.service.SChatMessageService;
import com.stellar.circle.constants.ErrorCodeConstants;
import com.stellar.circle.controller.admin.sChatMessage.vo.SChatMessageRequestPageVO;
import com.stellar.circle.controller.admin.sChatMessage.vo.SChatMessageResponseVO;
import com.stellar.circle.convert.SChatMessageConvert;
import com.stellar.circle.domain.sChatMessage.SChatMessageDomainService;

import com.stellar.core.context.LoginContextHolder;
import com.stellar.web.core.bean.PageResult;
import com.stellar.web.core.enums.IsDeletedFlagEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.stellar.circle.constants.CircleConstants.*;
import static com.stellar.core.util.ServiceExceptionUtil.exception;

/**
 * 私聊消息表领域服务实现
 *
 * @author Jqchan
 * @version 1.0
 * @date 2025-06-12 21:21:22
 */
@Service
public class SChatMessageDomainServiceImpl implements SChatMessageDomainService {

    @Resource
    private SChatMessageService sChatMessageService;

    @Override
    public PageResult<SChatMessageResponseVO> page(SChatMessageRequestPageVO requestPageVO) {
        PageResult<SChatMessageResponseVO> pageResult = new PageResult<>();
        SChatMessage queryEntity = SChatMessageConvert.INSTANCE.convert(requestPageVO);
        queryEntity.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());

        List<SChatMessage> entities = sChatMessageService.page(queryEntity,
                requestPageVO.getStart(), requestPageVO.getPageSize());

        if (entities.isEmpty()) {
            return pageResult;
        }

        Long count = sChatMessageService.count(queryEntity);
        List<SChatMessageResponseVO> vos = SChatMessageConvert.INSTANCE.convertEntityToRespList(entities);

        pageResult.setResult(vos);
        pageResult.setTotal(count.intValue());
        return pageResult;
    }

    @Override
    public Boolean delete(Long id) {
        SChatMessage entity = new SChatMessage();
        entity.setId(id);
        entity.setIsDeleted(IsDeletedFlagEnum.DELETED.getVal());
        return sChatMessageService.update(entity) != 0;
    }

    @Override
    public SChatMessage saveMessage(SChatMessage sChatMessage) {
        if (sChatMessage == null) {
            throw exception(ErrorCodeConstants.CIRCLE_PARAM_EMPTY);
        }
        if (sChatMessage.getSenderId() == null || sChatMessage.getReceiverId() == null) {
            throw exception(ErrorCodeConstants.CIRCLE_PARAM_EMPTY);
        }
        String conversationId = generateConversationId(sChatMessage.getSenderId(), sChatMessage.getReceiverId());
        sChatMessage.setConversationId(conversationId);
        sChatMessage.setIsRead(IS_READ_NO);
        sChatMessage.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
        // 如果没有传类型 - 默认为文本
        if (sChatMessage.getContentType() == null) {
            sChatMessage.setContentType(MESSAGE_TYPE_TEXT);
        }
        return sChatMessageService.insert(sChatMessage);
    }


    @Override
    public Boolean markAsRead(List<Long> messageId) {
        sChatMessageService.markAsRead(messageId);
        return true;
    }

    @Override
    public Integer getUnreadCount() {
        SChatMessage sChatMessage = new SChatMessage();
        sChatMessage.setReceiverId(LoginContextHolder.getUserId());
        sChatMessage.setIsRead(IS_READ_NO);
        sChatMessage.setIsHidden(IS_HIDDEN_NO);
        sChatMessage.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getVal());
        return sChatMessageService.count(sChatMessage).intValue();
    }

    @Override
    public PageResult<SChatMessageResponseVO> getMessageList(int page, int pageSize) {
        PageResult<SChatMessageResponseVO> pageResult = new PageResult<>();
        Long userId = LoginContextHolder.getUserId();
        Long count = sChatMessageService.countChatList(userId);
        if (count == 0) {
            return pageResult;
        }

        List<SChatMessageResponseVO> messages = sChatMessageService.getMessageList(userId, page, pageSize);

        pageResult.setTotal(count.intValue());
        pageResult.setResult(messages);

        return pageResult;
    }

    @Override
    public String generateConversationId(Long user1, Long user2) {
        long min = Math.min(user1, user2);
        long max = Math.max(user1, user2);
        return min + "_" + max;
    }

    @Override
    public List<SChatMessageResponseVO> getHistory(String conversationId, Long lastMsgId, int limit) {
        List<SChatMessage> messages = sChatMessageService.selectHistory(conversationId, lastMsgId, limit);
        return SChatMessageConvert.INSTANCE.convertEntityToRespList(messages);
    }

    @Override
    public void sendOfflineMessages(Long userId) {
        List<SChatMessage> unreadMessages = sChatMessageService.selectUnreadByUserId(userId);
        unreadMessages.forEach(msg -> {
//            webSocketHandler.sendToUser(userId, JSON.toJSONString(SChatMessageConvert.INSTANCE.convert(msg)));
//            markAsRead(Collections.singletonList(msg.getId()));
        });
    }

}